package com.neusoft.neuiotms.dcam.workflow.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import javax.persistence.EntityNotFoundException;
import javax.transaction.Transactional;

import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.neusoft.bizcore.activiti.dto.ProcessInstanceDTO;
import com.neusoft.bizcore.activiti.service.ProcessInstanceService;
import com.neusoft.bizcore.activiti.service.WorkOrderService;
import com.neusoft.bizcore.auth.common.bean.UserBean;
import com.neusoft.bizcore.web.constant.ExceptionConstants;
import com.neusoft.bizcore.web.exception.UnitedException;
import com.neusoft.neuiotms.dcam.anhui.itsm.WorkflowBean;
import com.neusoft.neuiotms.dcam.constant.DCAMConsts;
import com.neusoft.neuiotms.dcam.fixed.dto.AssetLifeCycleDTO;
import com.neusoft.neuiotms.dcam.fixed.model.Asset;
import com.neusoft.neuiotms.dcam.fixed.repository.AssetRepository;
import com.neusoft.neuiotms.dcam.fixed.service.AssetLifeCycleService;
import com.neusoft.neuiotms.dcam.fixed.service.AssetService;
import com.neusoft.neuiotms.dcam.fixed.service.ItsmService;
import com.neusoft.neuiotms.dcam.workflow.converter.ITSMApproveConverter;
import com.neusoft.neuiotms.dcam.workflow.converter.WeixiuKJConverter;
import com.neusoft.neuiotms.dcam.workflow.dto.ITSMApproveDTO;
import com.neusoft.neuiotms.dcam.workflow.dto.WeixiuItemKJDTO;
import com.neusoft.neuiotms.dcam.workflow.dto.WeixiuKJDTO;
import com.neusoft.neuiotms.dcam.workflow.model.ITSMApprove;
import com.neusoft.neuiotms.dcam.workflow.model.WeixiuItemKJ;
import com.neusoft.neuiotms.dcam.workflow.model.WeixiuKJ;
import com.neusoft.neuiotms.dcam.workflow.repository.ITSMApproveRepository;
import com.neusoft.neuiotms.dcam.workflow.repository.WeixiuItemKJRepository;
import com.neusoft.neuiotms.dcam.workflow.repository.WeixiuKJRepository;
import com.neusoft.neuiotms.dcam.workflow.service.WeixiuKJService;

import io.micrometer.core.instrument.util.StringUtils;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class WeixiuKJServiceImpl implements WeixiuKJService {

    @Autowired
    private WorkOrderService workOrderService;
    @Autowired
    private ProcessInstanceService processInstanceService;
    @Autowired
    private WeixiuKJRepository weixiuKJRepository;
    @Autowired
    private WeixiuKJConverter weixiuKJConverter;
    @Autowired
    private ITSMApproveRepository approveRepository;
    @Autowired
    private ITSMApproveConverter approveConverter;
    @Autowired
    private WeixiuItemKJRepository weixiuItemKJRepository;
    @Autowired
    private AssetRepository assetRepository;
    @Autowired
    private AssetService assetService;
    @Autowired
    private AssetLifeCycleService assetLifeCycleService;
    @Autowired
    private ItsmService itsmService;

    @Override
    @Transactional
    public WeixiuKJDTO create(final WeixiuKJDTO dto, final UserBean user) {

        final String taskId = dto.getTaskId();
        final ProcessInstanceDTO instance =
                this.workOrderService.submit(dto.getTitle(), DCAMConsts.PROCESSS_WEIXIU_KJ_KEY, dto.getWorkOrderNum(),
                        user);
        dto.setTaskId(instance.getTaskId());
        dto.setWorkOrderNum(instance.getWorkorderNum());
        dto.setCreateUser(user.getUsername());
        dto.setCreateUserName(user.getName());

        // 查询当前workOrderNum和TaskId下是否存在记录
        final WeixiuKJ oldModel = this.weixiuKJRepository.findByWorkOrderNumAndTaskId(
                dto.getWorkOrderNum(), taskId);
        if (oldModel == null) {
            dto.setId(null);
        }

        // 解锁以前的资产信息
        final List<WeixiuItemKJ> all = this.weixiuItemKJRepository.findByMain_WorkOrderNum(dto.getWorkOrderNum());
        if (null != all) {
            this.assetService.updateLocked(all.stream().map(l -> l.getCode()).distinct().collect(Collectors.toList()),
                    false);
        }

        WeixiuKJ model = this.weixiuKJConverter.toModel(dto);
        model = this.weixiuKJRepository.save(model);

        // 枷锁资产信息
        this.assetService.updateLocked(
                model.getDetails().stream().map(l -> l.getCode()).distinct().collect(Collectors.toList()),
                true);

        // 完成当前节点
        this.processInstanceService.complete(dto.getWorkOrderNum(), dto.getTaskId(), user);

        try {
            // 对接ITSM
            final List<WorkflowBean.AssetBean> assetList = Lists.newArrayList();
            for (final WeixiuItemKJDTO item : dto.getDetails()) {
                final WorkflowBean.AssetBean assetBean = WorkflowBean.AssetBean.builder()
                        .assetId(item.getCode())
                        .assetClassID(item.getSmallTypeCode())
                        .assetModel(item.getSpecifications())
                        .assetUnit("未知")
                        .assetPrice(0)
                        .assetNumber(1)
                        .assetName(item.getName())
                        .assetType("1")
                        .assetSign("未知")
                        .build();
                assetList.add(assetBean);
            }

            final WorkflowBean workflowBean = WorkflowBean.builder()
                    .workNum(dto.getWorkOrderNum())
                    .workName("设备维修")
                    .workType("40")
                    .workContent("设备维修申请")
                    .applyUser(user.getUsername())
                    .assetList(assetList)
                    .build();

            this.itsmService.pushItsm(workflowBean);
        } catch (final Exception e) {
            WeixiuKJServiceImpl.log.error("设备维修流程推送ITSM时发生错误", e);
        }

        return this.weixiuKJConverter.toDTO(model);
    }

    @Override
    public WeixiuKJDTO detail(final String workOrderNum, final String taskId, final UserBean user) {
        WeixiuKJ model = null;
        try {
            if (StringUtils.isNotBlank(workOrderNum) && !"NULL".equals(taskId)) {
                model = this.weixiuKJRepository.findByWorkOrderNumAndTaskId(workOrderNum, taskId);
                if (model == null) {
                    // 获取前一节点的TaskID
                    final String lastTaskId = this.processInstanceService.getLastTaskId(taskId, user);
                    if (lastTaskId == null) {
                        return new WeixiuKJDTO();
                    } else {
                        model = this.weixiuKJRepository.findByWorkOrderNumAndTaskId(workOrderNum,
                                lastTaskId);
                    }
                }
            } else if ("NULL".equals(taskId)) {
                final List<WeixiuKJ> WeixiuKJs =
                        this.weixiuKJRepository.findAllByWorkOrderNumOrderByCreateTimeDesc(workOrderNum);
                if ((WeixiuKJs != null) && (WeixiuKJs.size() > 0)) {
                    model = WeixiuKJs.get(0);
                }
            }
        } catch (final EntityNotFoundException e) {
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND,
                    new Object[] {workOrderNum },
                    new Object[] {taskId });
        }
        return this.weixiuKJConverter.toDTO(model);
    }

    @Override
    @Transactional
    public ITSMApproveDTO itsmCreate(final ITSMApproveDTO dto, final UserBean user) {
        final ITSMApprove model = this.approveConverter.toModel(dto);
        this.approveRepository.save(model);

        this.processInstanceService.setGlobalVariable(dto.getTaskId(), DCAMConsts.PROCESSS_WEIXIU_KJ_APPROVE_RESULT,
                dto.getResult());
        // 完成当前节点
        this.processInstanceService.complete(dto.getWorkOrderNum(), dto.getTaskId(), user);

        // 如果审批同意的情况下创建资产信息
        if ("1".equals(dto.getResult())) {
            // 更新资产状态为待维修
            final List<WeixiuKJ> models =
                    this.weixiuKJRepository.findAllByWorkOrderNumOrderByCreateTimeDesc(dto.getWorkOrderNum());
            if ((models != null) && (models.size() > 0)) {
                final List<String> codes = models.get(0).getDetails().stream().map(l -> l.getCode()).distinct()
                        .collect(Collectors.toList());
                this.assetService.updateStatus(codes, DCAMConsts.ASSET_STATUS_UNMAINTENANCE);
            }
        }

        return this.approveConverter.toDTO(model);
    }

    @Override
    public ITSMApproveDTO itsmDetails(final String workOrderNum, final String taskId, final UserBean user) {
        ITSMApprove model = null;
        try {
            if (StringUtils.isNotBlank(workOrderNum) && !"NULL".equals(taskId)) {
                model = this.approveRepository.findByWorkOrderNumAndTaskId(workOrderNum, taskId);
                if (model == null) {
                    // 获取前一节点的TaskID
                    final String lastTaskId = this.processInstanceService.getLastTaskId(taskId, user);
                    if (lastTaskId == null) {
                        return new ITSMApproveDTO();
                    } else {
                        model = this.approveRepository.findByWorkOrderNumAndTaskId(workOrderNum,
                                lastTaskId);
                    }
                }
            } else if ("NULL".equals(taskId)) {
                final List<ITSMApprove> WeixiuKJs =
                        this.approveRepository.findAllByWorkOrderNumOrderByCreateTimeDesc(workOrderNum);
                if ((WeixiuKJs != null) && (WeixiuKJs.size() > 0)) {
                    model = WeixiuKJs.get(0);
                }
            }
        } catch (final EntityNotFoundException e) {
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND,
                    new Object[] {workOrderNum },
                    new Object[] {taskId });
        }
        return this.approveConverter.toDTO(model);
    }

    @Transactional
    @Override
    public void confirmCreate(final WeixiuKJDTO dto, final UserBean user) {
        this.processInstanceService.complete(dto.getWorkOrderNum(), dto.getTaskId(), user);
        // 更新资产状态为再用
        final List<WeixiuKJ> models =
                this.weixiuKJRepository.findAllByWorkOrderNumOrderByCreateTimeDesc(dto.getWorkOrderNum());

        if ((models != null) && (models.size() > 0)) {
            final WeixiuKJ model = models.get(0);

            // 修改维修金额
            dto.getDetails().forEach(l -> {
                model.getDetails().forEach(s -> {
                    if (l.getId().toString().equals(s.getId().toString())) {
                        s.setAmount(l.getAmount());
                    }
                });
            });

            this.weixiuItemKJRepository.saveAll(model.getDetails());

            this.weixiuKJCompleteUpdate(model);
        }

    }

    @Override
    public WeixiuKJDTO confirmDetails(final String workOrderNum, final String taskId, final UserBean user) {
        final List<WeixiuKJ> WeixiuKJs =
                this.weixiuKJRepository.findAllByWorkOrderNumOrderByCreateTimeDesc(workOrderNum);
        if ((WeixiuKJs != null) && (WeixiuKJs.size() > 0)) {
            return this.weixiuKJConverter.toDTO(WeixiuKJs.get(0));
        }
        return new WeixiuKJDTO();
    }

    private void weixiuKJCompleteUpdate(final WeixiuKJ model) {
        final List<AssetLifeCycleDTO> lifeList = new ArrayList<>();
        final List<Asset> assets = new ArrayList<>();
        model.getDetails().stream().map(l -> {
            final Asset asset = this.assetRepository.findByCode(l.getCode());
            asset.setLocked(false);
            asset.setStatus(l.getStatus());

            // 生命周期
            lifeList.add(AssetLifeCycleDTO.builder().code(l.getCode())
                    .lifeCycle(DCAMConsts.ASSET_LIFE_TYPE_WEIXIU)
                    .content(l.getName() + "已维修").workNum(model.getWorkOrderNum()).build());

            return asset;
        }).forEach(assets::add);

        if (assets.size() > 0) {
            this.assetRepository.saveAll(assets);
        }

        if (lifeList.size() > 0) {
            this.assetLifeCycleService.batchCreate(lifeList);
        }

    }

}
